package com.yeswater.multithread.chapter4;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * author : yeswater
 * date : 2023/10/23
 */

public class Run_4_1_2 {
    public static void main(String[] args) {
        MyService service = new MyService();
        ThreadA threadA = new ThreadA(service);
        threadA.setName("A");
        threadA.start();

        ThreadA threadAA = new ThreadA(service);
        threadAA.setName("AA");
        threadAA.start();

        ThreadB threadB = new ThreadB(service);
        threadB.setName("B");
        threadB.start();

        ThreadB threadBB = new ThreadB(service);
        threadBB.setName("BB");
        threadBB.start();
    }

    private static class ThreadA extends Thread{
        private final MyService service;

        public ThreadA(MyService service) {
            this.service = service;
        }

        @Override
        public void run() {
            service.methodA();
        }
    }

    private static class ThreadB extends Thread{
        private final MyService service;

        public ThreadB(MyService service) {
            this.service = service;
        }

        @Override
        public void run() {
            service.methodB();
        }
    }

    private static class MyService {
        private final Lock lock = new ReentrantLock();

        public void methodA() {
            try {
                lock.lock();
                System.out.println("methodA begin ThreadName=" + Thread.currentThread().getName()
                        + " time=" + System.currentTimeMillis());
                Thread.sleep(5000);
                System.out.println("methodA   end ThreadName=" + Thread.currentThread().getName()
                        + " time=" + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void methodB() {
            try {
                lock.lock();
                System.out.println("methodB begin ThreadName=" + Thread.currentThread().getName()
                        + " time=" + System.currentTimeMillis());
                Thread.sleep(5000);
                System.out.println("methodB   end ThreadName=" + Thread.currentThread().getName()
                        + " time=" + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
